import json
import requests
import random
import sched
import hashlib
import urllib3
import time
from datetime import datetime
today = datetime.today().weekday()#获取今天星期几

urllib3.disable_warnings()
# requests.packages.urllib3.disable_warnings()
# =================用户配置  可修改=======================
phone=""          #账号
password=""      #密码
country=""                   #国家
province=""             #省
city=""                  #城市
address=""       #地址
lat=""                  #纬度   https://lbs.amap.com/tools/picker 根据地址找经纬度   
lon=""                 #经度   https://lbs.amap.com/tools/picker 根据地址找经纬度  
#打卡类型，START和END，START 上班，END 下班  执行时间会改变 这里默认11点前上班 不然下班 具体参考55行
types="START"                     
description=""
sec=100 #随机在0~sec秒执行打卡
isWeekCloak=True #周末是否打卡  True 可以  False 不可
serveSendKey=""#serve酱KEY http://sc.ftqq.com/?c=wechat&a=bind
#===================基础变量不建议修改=============================
def getNowHour(oldTime): #时间换算
    if(oldTime + 8 > 24):
        return oldTime + 8 - 24
    else:
        return oldTime + 8
        
now_hour = getNowHour(time.gmtime()[3])  #获取中国时间 小时
typeDec=''#上班类型
# =================脚本配置(不可擅自更改)=======================
inc = random.randint(0,sec)
schedule = sched.scheduler(time.time, time.sleep)
ran=random.uniform(-0.003,0.003)#随机300m坐标
latitude=str(ran+float(lat))
longitude=str(ran+float(lon))
Login_Url='https://api.moguding.net:9000/session/user/v1/login'
planUrl = "https://api.moguding.net:9000/practice/plan/v3/getPlanByStu"
saveUrl = "https://api.moguding.net:9000/attendence/clock/v2/save"
salt="3478cbbc33f84bd00d75d7dfa69e0daa"
token = ""
headers={
        'Accept-Language':"zh-CN,zh;q=0.8",
        'roleKey': 'student',
        'Host':'api.moguding.net:9000',
        "Content-Type": "application/json; charset=UTF-8",
        "Cache-Control": "no-cache",
        'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.1; MX4 Build/F2P4MZ) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/41.0.3191.83 Mobile Safari/537.36',
        }
if(now_hour < 11):
    types = "START"
    typeDec='上班'
else:
    types = "END"
    typeDec='下班'
body = {
        "country":country,
        "address":address,
        "province":province,
        "city":city,
        "latitude":latitude,
        "description":description,
        "type":types,
        "device":"Android",
        "longitude":longitude
        }

# ===============================serve酱推送=====================
def sendMsg(title, desp):
    url = "https://sctapi.ftqq.com/"+serveSendKey+".send"
    body = {
        "title": title,
        "desp": desp
    }
    res = requests.post(url=url, data=body)
    # print(res.text)
# =================生成签名===================
def GenerateSign(x):
    a = x.encode('utf-8')
    a = hashlib.md5(a).hexdigest() 
    # print(a)
    return a
# ================登录====================
def login():
    
    global token,userId,name
    data = {
            "password": password,
            "loginType": "android",
            "uuid": "",
            "phone": phone
        }
    req = requests.post(Login_Url,data=json.dumps(data),headers=headers,verify=False)
    text = req.json()
    new_token = text["data"]["token"]
    name=text["data"]["nikeName"]
    token=json.loads(req.text)['data']['token']
    userId=json.loads(req.text)['data']['userId']
# ===================获取planID=======================
def getPlanId():
    login()
    
    global planId
    data = {"state": ""}
    headers["Authorization"]=token 
    # sign= userId+"student"+salt
    headers["sign"]=GenerateSign(userId+"student"+salt)
    req = requests.post(planUrl,data=json.dumps(data),headers=headers)
    req.headers.keys
    planId=json.loads(req.text)['data'][0]['planId']
   
# =======================开始打卡=======================
def main():
    getPlanId()
    
     # sign= device + type + planID + userId + Address + salt
    body["planId"]=planId
    headers["sign"]=GenerateSign(body["device"]+body["type"]+planId+userId+body["address"]+salt)
    req = requests.post(saveUrl,data=json.dumps(body),headers=headers)
    req_json=json.loads(req.text)
    

    if(req_json["code"]==200):
        print(name+"打卡成功")
        sendMsg("Hi,"+name+typeDec+"打卡成功","打卡状态："+req_json["msg"]+"\n\n打卡地点："+address+"\n\n打卡时间："+req_json["data"]["createTime"])
    else:
        print(name+"打卡失败")
        sendMsg("蘑菇丁打卡失败","打卡失败"+"\n\n失败原因："+req_json["msg"])

if(isWeekCloak):
    schedule.enter(inc, 0, main, ())
    schedule.run()
else:
    if(today<5):
        schedule.enter(inc, 0, main, ())
        schedule.run()
    else:
        print("周末不签到") 